package com.gopay.commons.validator.check;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.gopay.commons.validator.form.Field;
import com.gopay.commons.validator.form.Validator;

/**
 * 正则表达式校验
 * 
 * @DefaultPatternValidator.java
 * @author yaobo
 * @2012-12-26 上午09:55:28 www.gopay.com.cn Inc.All rights reserved.
 */
public class DefaultPatternValidator extends DefaultValidator {
    @Override
    protected boolean validator(Field field) {
        if (field == null) {
            return true;
        }

        List<Validator> validators = field.getValidators();
        if (validators == null || validators.size() == 0) {
            return true;
        }

        Validator validator = null;
        for (Iterator<Validator> it = validators.iterator(); it.hasNext();) {
            validator = (Validator) it.next();
            if (StringUtils.isNotBlank(validator.getPattern())) {
                String value = (String) field.getValue();

                Pattern pattern = Pattern.compile(validator.getPattern());
                Matcher matcher = pattern.matcher(value);
                boolean flag = matcher.find();
                if (!flag) {
                    return false;
                }

                break;
            }
        }

        return true;
    }
}
